<template>
  <div class="app-container home">
    <el-card class="box-card">
      <!-- 服务器总览 -->
      <el-row :gutter="20">
        <el-col :sm="24" :lg="24">
          <div style="display: flex;align-items: center;justify-content: space-between;height: 3vw"><b>服务器总览</b><div><el-button icon="el-icon-refresh" size="mini" @click="refresh" style="margin-right: 1vw">获取最新数据</el-button><b>数据同步时间：{{dataSynchronizationTime}}</b></div>  </div>
          <el-table :data="getServerCurrentPageData" style="width: 100%" border>
            <el-table-column prop="serverAddress" label="服务器名称"></el-table-column>
            <el-table-column prop="serverName" label="业务系统"></el-table-column>
            <el-table-column prop="storage" label="内存">
              <template slot-scope="scope">
                {{ numChange(scope.row.storage) }}
              </template>
            </el-table-column>
            <el-table-column prop="totalNuclearNumber" label="总核数"></el-table-column>
            <el-table-column prop="rootPartitionUsage" label="根分区使用率">
              <template slot-scope="scope" v-if="scope.row.rootPartitionUsage">
                {{ numFilter(scope.row.rootPartitionUsage,2) }}%
              </template>
            </el-table-column>
            <el-table-column prop="memoryUsage" label="内存使用率">
              <template slot-scope="scope" v-if="scope.row.memoryUsage">
                {{ numFilter(scope.row.memoryUsage,2) }}%
              </template>
            </el-table-column>
            <el-table-column prop="systemLoad" label="系统负载"></el-table-column>
          </el-table>
          <el-pagination
            :page-size="pageSizeServer"
            :total="serviceData.length"
            @current-change="handleServerCurrentChange">
          </el-pagination>

        </el-col>
      </el-row>
      <!-- 服务器选择 -->
      <el-row class="mar_t_15">
        <el-form :inline="true">
          <el-form-item label="服务功能">
            <el-select v-model="serviceKeyName" placeholder="请选择服务功能" @change="changeServerName">
              <el-option
                v-for="(item, index) in serverNameList"
                :value="item"
                :key="index"
              >{{ item }}</el-option
              >
            </el-select>
          </el-form-item>
          <el-form-item label="服务器选择">
            <el-select v-model="serviceKeyword" placeholder="请选择服务器" @change="changeServer">
              <el-option
                v-for="(item, index) in serviceList"
                :value="item"
                :key="index"
                >{{ item }}</el-option
              >
            </el-select>
          </el-form-item>
          <el-button icon="el-icon-refresh" size="mini" @click="refreshSelect" >重置</el-button>
        </el-form>
      </el-row>
      <!-- CPU -->

      <el-row :gutter="20" v-if="isShow">
        <p class="mar_l_10"><b>CPU</b></p>
        <el-col :span="6">
          <el-card class="box-card">
            <div class="card_height">
              <p>CPU核数</p>
              <div class="number" >{{data.cpu.cpu_core_number_query[0].value[1]}}</div>
            </div>
          </el-card>
          <el-card class="box-card mar_t_15">
            <div class="card_height">
              <p>空闲率</p>
              <div class="number" >{{numFilter(data.cpu.cpu_idel_percent_query[0].value[1],1)}}%</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="box-card">
            <div>
              <p class="text-center">内核空间占用CPU百分比</p>
              <liquidfill ref="space_cpu" id="space_cpu" :size="this.numFilterCpu(this.data.cpu.cpu_system_percent_query[0].value[1]/100)"></liquidfill>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="box-card">
            <div>
              <p class="text-center">用户空间占用CPU百分比</p>
              <!-- <liquidfill id="user_space_cpu" :size="server.cpu.used/100"></liquidfill> -->
              <liquidfill id="user_space_cpu" :size="this.numFilterCpu(data.cpu.cpu_user_persent_query[0].value[1]/100)"></liquidfill>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="box-card">
            <div class="card_height_one">
              <p>等待输入输出的CPU时间百分比</p>
              <div class="number">{{numFilter(data.cpu.cpu_iowait_persent_query[0].value[1],2)}}%</div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" v-if="isShow">
        <p class="mar_l_10"><b>内存</b></p>
        <el-col :span="6">
          <el-card class="box-card">
            <div class="card_height">
              <p>可用内存</p>
              <div class="number">{{numChange(data.mem.mem_free_size_query[0].value[1])}}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="box-card">
            <div class="card_height">
              <p>内存使用率</p>
<!--              mem_swap_total_size_query-->
              <div class="number">{{numFilter(data.mem.mem_use_percent_query[0].value[1],1)}}%</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="box-card">
            <div class="card_height">
              <p>总内存</p>
              <div class="number">{{numChange(data.mem.mem_total_query[0].value[1])}}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="box-card">
            <div class="card_height">
              <p>缓存</p>
              <div class="number">{{numChange(data.mem.mem_cache_size_query[0].value[1])}}</div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" v-if="isShow">
        <p class="mar_l_10"><b>负载</b></p>
        <el-col :span="6">
          <el-card class="box-card">
            <div class="card_height">
              <p>1分钟负载</p>
              <div class="number">{{numFilter(data.load.load1_query[0].value[1],2)}}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="box-card">
            <div class="card_height">
              <p>5分钟负载</p>
              <div class="number">{{numFilter(data.load.load5_query[0].value[1],2)}}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="box-card">
            <div class="card_height">
              <p>15分钟负载</p>
              <div class="number">{{numFilter(data.load.load15_query[0].value[1],2)}}</div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-row v-if="isShow">
        <p class="mar_l_10"><b>文件系统</b></p>
        <el-table :data="getServerFileCurrentPageData" style="width: 100%" border class="mar_b_10">
            <el-table-column  prop="device" label="文件系统"></el-table-column>
            <el-table-column  prop="total" label="容量"></el-table-column>
            <el-table-column  prop="use" label="已用"></el-table-column>
            <el-table-column  prop="free" label="可用"></el-table-column>
            <el-table-column  prop="usePercent" label="已用%"></el-table-column>
            <el-table-column  prop="mountpoint" label="挂载点"></el-table-column>
        </el-table>
        <el-pagination
          :page-size="pageSizeServerFile"
          :total="dataFileSystemList.length"
          @current-change="handleServerFileCurrentChange">
        </el-pagination>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card class="box-card">
              <div class="card_height">
                <p>空闲存储空间</p>
                <div class="number">{{totalFreeFileSystem}}</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="box-card">
              <div class="card_height">
                <p>文件系统大小</p>
                <div class="number">{{totalFileSystem}}</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="box-card">
              <div class="card_height">
                <p>磁盘读取总量</p>
                <div class="number">{{totalRead}}</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="box-card">
              <div class="card_height">
                <p>磁盘写入总量</p>
                <div class="number">{{totalWrite}}</div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-row>

      <el-row v-if="isShow">
        <p><b>网卡列表</b></p>
        <el-table :data="getCurrentPageData" style="width: 100%" border>
          <el-table-column prop="device" label="接口"></el-table-column>
          <el-table-column prop="inetAddr" label="inet addr"></el-table-column>
          <el-table-column prop="up" label="上传流量(单位MB)">
            <template slot-scope="scope">
              {{ numChangeMB(scope.row.up) }}
            </template>
          </el-table-column>
          <el-table-column prop="down" label="下载流量(单位MB)">
            <template slot-scope="scope">
              {{ numChangeMB(scope.row.down) }}
            </template>
          </el-table-column>

        </el-table>
        <el-pagination
          :page-size="pageSize"
          :total="dataNetList.length"
          @current-change="handleCurrentChange">
        </el-pagination>
      </el-row>

      <el-row :gutter="20" v-if="data.system_run_time">
        <p class="mar_l_10"><b>操作系统</b></p>
        <el-col :span="6" v-if="isShow">
          <el-card class="box-card">
            <div class="card_height_110">
              <p>运行时间</p>
              <div class="number">{{dateChange(data.system_run_time.system_run_time[0].value[1])}}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="box-card">
            <div class="card_height_110">
              <p>是否运行</p>
              <div class="number" v-if="isShow">运行</div>
              <div class="number" v-if="!isShow">停止</div>
            </div>
          </el-card>
        </el-col>
      </el-row>

    </el-card>
  </div>
</template>

<script>
import liquidfill from "@/components/Liquidfill/index";
import { listPropertyInfo,listPropertyInfoAddress } from "@/api/asset/propertyInfo";
import {getMonitorData,getMonitorDataList} from "@/api/workOrder/monitor"

export default {
  name: "Index",
  props: ['currentProject'],
  data() {
    return {
      // 服务器信息
      server: [],
      serviceData: [],
      fileData: [],
      networkData: [],
      serviceKeyword: "",
      serviceKeyName: "",
      serviceList: [],
      data:{},
      totalFreeFileSystem:"",
      totalFileSystem:"",
      dataFileSystemList:[],
      dataNetList:[],
      totalWrite:"",
      totalRead:"",
      pageSizeServer:5,
      currentPageServer:1,
      pageSize:5,
      currentPage:1,
      currentPageServerFile:1,
      pageSizeServerFile:5,
      query:{
        id:"",
        projectCode:"",
        serverAddress:"",
        data:"",
        isDeleted:0
      },
      dataSynchronizationTime:"",
      isShow:false,
      serverNameList:[],
    };
  },
  components: {
    liquidfill,
  },
  created() {
     this.getServerList();
  },
  mounted() {
    // 10分钟的毫秒数
    //const interval = 10 * 60 * 1000;
    const interval = 10 * 60 * 1000;

    // 刷新页面的函数
    const refreshPage = () => {
      this.serviceKeyName=""
      this.changeServerName();
      this.getServerList();
    };

    // 每10分钟执行一次刷新页面的操作
    setInterval(refreshPage, interval);
  },
  methods: {

    handleCurrentChange(page) {
      this.currentPage = page;
    },
    handleServerFileCurrentChange(page) {
      this.currentPageServerFile = page;
    },
    handleServerCurrentChange(page) {
      this.currentPageServer = page;
    },
    refresh(){
      this.$router.go(0);
      /*this.serviceKeyName=""
      this.changeServerName();
      this.getServerList();*/

    },
    refreshSelect(){
      this.serviceKeyName=""
      this.changeServerName();
      this.getServerList();
    },
    dateChange(value){
      let seconds = Math.floor(value / 1000);
      let hours = Math.floor(seconds / 3600);
      let minutes = Math.floor((seconds % 3600) / 60);
      return hours + "时 " + minutes + "分";
    },
    changeServerName(){
      this.query.serverName=this.serviceKeyName;
      this.query.projectCode=this.currentProject;
      listPropertyInfoAddress(this.query).then(response => {
        this.serviceList = response.rows.map(item => item.serverAddress);
        this.loading = false;
      }).then(res => {
        this.serviceKeyword = this.serviceList[0];
        this.getSeverMonitorData();
        this.getServiceData();
      })
    },
    changeServer(){
      //echart_space_cpu
      //echart_user_space_cpu
      // 每次获取数据之前 先通过id 获取这两个dom 将他们移除
      // document.getElementById("echart_space_cpu")
      // const el =
      // console.log( document.getElementById("echart_space_cpu"),"在这")
      // el.parentNode.removeChild(el);

      this.dataFileSystemList=[];
      console.log(this.serviceKeyword,"change")
      this.getSeverMonitorData();
    },
    numFilterCpu(value){
      let realVal = parseFloat(value).toFixed(2);
      if(realVal==0){
        return  parseFloat(value).toFixed(3)
      }
      return realVal
    },

    numFilter(value,num) {
      let realVal = parseFloat(value).toFixed(num);
      return realVal;
    },
    numChangeMB(value){
      if (!value){
        return "";
      }
      else{
        if(value/1024/1024>0.01){
          return this.numFilter(value/1024/1024,2)+"MB";
        }else {
          return "0MB"
        }
      }
    },
    numChange(value){
      if (!value){
        return "";
      }
      if (value>1024*1024*1024*1024){
        return this.numFilter(value/1024/1024/1024/1024,2)+"T";
      }
      if (value>1024*1024*1024){
        return this.numFilter(value/1024/1024/1024,2)+"G";
      }
      else if (value>1024*1024){
        return this.numFilter(value/1024/1024,2)+"M";
      }
      else if (value>1024){
        return this.numFilter(value/1024,0)+"K"
      }
      else {
        return this.numFilter(value)+"B"
      }
      },
    getDisk(disks){
      let number=0;
      for (const disk of disks) {
        number+=(Number(disk.value[1]))
      }
      return this.numFilter((number/1024/1024),2);
    },
    getServerList() {
      this.query.projectCode=this.currentProject;
      listPropertyInfoAddress(this.query).then(response => {
        this.serviceList = response.rows.map(item => item.serverAddress);
        this.serverNameList = [...new Set(response.rows.map(item => item.serverName))];
        this.loading = false;
      }).then(res => {
        this.serviceKeyword = this.serviceList[0];
        console.log(this.serviceKeyword)
        this.getSeverMonitorData();
        this.getServiceData();
      })
    },
    getSeverMonitorData(){
      this.query.serverAddress=this.serviceKeyword
      getMonitorData(this.query).then(response=>{
        if (response){
          this.dataSynchronizationTime=response.createTime
          this.data=JSON.parse(response.data)
          if (this.data.cpu.cpu_core_number_query.length>0){
            this.isShow=true
            this.getList();
          }else {
            this.isShow=false
            this.$message.warning('监控数据为空');
          }


        }else {
          this.data={};
          this.isShow=false
          this.$message.warning('不存在监控数据');
        }
      })
    },
    /** 查询服务器信息 */
    getList() {
      let diskFreeSizeQuery = this.data.disk.disk_free_size_query;
      let totalSizeQuery = this.data.disk.disk_total_size_query;
      let usePercentQuery = this.data.disk.disk_use_percent_query;
      let totalFreeFileSystem = 0;
      let totalFileSystem=0;
      this.dataFileSystemList=[]
      for (let i = 0; i < diskFreeSizeQuery.length; i++) {
        totalFreeFileSystem+=Number(diskFreeSizeQuery[i].value[1]);
        totalFileSystem+=Number(totalSizeQuery[i].value[1]);
        let dataFileSystem ={
          "mountpoint":diskFreeSizeQuery[i].metric.mountpoint,
          "device":diskFreeSizeQuery[i].metric.device,
          "free":this.numChange(diskFreeSizeQuery[i].value[1]),
          "total":this.numChange(totalSizeQuery[i].value[1]),
          "usePercent":this.numFilter(usePercentQuery[i].value[1],2)+"%",
          "use":this.numChange(((totalSizeQuery[i].value[1]))- ((diskFreeSizeQuery[i].value[1])))
        }
        this.dataFileSystemList.push(dataFileSystem);
      }
      this.totalFreeFileSystem = this.numChange(totalFreeFileSystem);
      this.totalFileSystem=this.numChange(totalFileSystem);

      let totalWrite = 0;
      let totalRead=0;
      let netDownQuery = this.data.net.net_down_query;
      let netUpQuery = this.data.net.net_up_query;
      this.dataNetList=[];
      for (let i = 0; i < netDownQuery.length; i++) {
        const netDownQuery1 = netDownQuery[i];
        const netUpQuery1 = netUpQuery[i];
        totalWrite +=Number(netUpQuery1.value[1])
        totalRead +=Number(netDownQuery1.value[1])
        let netData={
          "device":netDownQuery1.metric.device,
          "inetAddr":netDownQuery1.metric.instance,
          "down":this.numFilter(netDownQuery1.value[1],1),
          "up":this.numFilter(netUpQuery1.value[1],1)
        }
        this.dataNetList.push(netData);
      }
      this.totalWrite=this.numChange(totalWrite)
      this.totalRead=this.numChange(totalRead)

    },
    getServiceData() {
      this.query.projectCode=this.currentProject
      getMonitorDataList(this.query).then(response=>{
        this.serviceData=response;
      })
    },
  },
  computed: {
    getCurrentPageData() {
      const startIndex = (this.currentPage - 1) * this.pageSize;
      const endIndex = startIndex + this.pageSize;
      return this.dataNetList.slice(startIndex, endIndex);
    },
    getServerFileCurrentPageData() {
      const startIndex = (this.currentPageServerFile - 1) * this.pageSizeServerFile;
      const endIndex = startIndex + this.pageSizeServerFile;
      return this.dataFileSystemList.slice(startIndex, endIndex);
    },
    getServerCurrentPageData() {
      const startIndex = (this.currentPageServer - 1) * this.pageSizeServer;
      const endIndex = startIndex + this.pageSizeServer;
      return this.serviceData.slice(startIndex, endIndex);
    },
  }
};
</script>

<style scoped lang="scss">
.home {
  font-family: "open sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 13px;
  color: #676a6c;
  overflow-x: hidden;

  .mar_t_15 {
    margin-top: 10px;
  }

  .card_height {
    height: 96px;
    text-align: center;
    display: flex;
    flex-direction: column;
  }
  .card_height_one {
    height: 240px;
    text-align: center;
    display: flex;
    flex-direction: column;
    justify-content: center;
  }
  .card_height_110 {
    height: 110px;
    text-align: center;
    display: flex;
    flex-direction: column;
  }
  .number {
    font-weight: bold;
    font-size: 24px;
  }
  .introduce {
    font-weight: bold;
    line-height: 22px;
  }
  .text-center {
    text-align: center;
  }
  .mar_l_10 {
    margin-left: 10px;
  }
  .mar_b_10 {
    margin-bottom: 10px;
  }
}
</style>
